"""
基于python实现桶的相关操作
"""
import baidubce
from baidubce import exception
from baidubce.auth import bce_credentials
from baidubce import bce_client_configuration
from baidubce.services.bos import bos_client, canned_acl

from web import models
from django.conf import settings



def get_config(region):
    config = bce_client_configuration.BceClientConfiguration(
        credentials=bce_credentials.BceCredentials(
            access_key_id=settings.BOS_ACCESS_KEY_ID,
            secret_access_key=settings.BOS_SECRET_ACCESS_KEY,
        ),
        endpoint=region,
        protocol=baidubce.protocol.HTTPS
    )
    return config


def create_bucket(request, bucket, region='fsh.bcebos.com'):
    """
    创建桶
    :param request: 请求信息
    :param bucket: 桶名称
    :param region: 区域
    """
    config = get_config(region)

    # 获取客户端对象
    client = bos_client.BosClient(config)

    # 创建桶
    # if not client.does_bucket_exist(bucket):
    client.create_bucket(bucket)
    #
    client.set_bucket_canned_acl(bucket, canned_acl.PUBLIC_READ)

    # 设置指定用户对Bucket的访问权限
    # client.set_bucket_acl(
    #     bucket,
    #     [{'grantee': [{'id': '0067310b32594e91aeafce9f1028e9a2'}, ],
    #       'permission': ['FULL_CONTROL'],
    #       'resource': [bucket + '/prefix/*']
    #       }]
    # )

    # 解决跨域问题
    conf = {
        'allowedOrigins': ['*'],  # ['http://www.boluor.com'],
        'allowedMethods': ['GET', 'HEAD', 'DELETE', 'POST', 'PUT'],
        'allowedHeaders': ['*'],
        'allowedExposeHeaders': ['ETag', 'Content-Length', 'x-bce-next-append-offset', 'x-bce-object-type',
                                 'x-bce-request-id'],
        'maxAgeSeconds': 1800,
    }
    # 每个Bucket最多允许有100条规则: [conf, ...]
    client.put_bucket_cors(bucket, [conf, ])


def upload_file(bucket_name, obj_key, region='fsh.bcebos.com', file_obj=None):
    """ 分块上传 """
    config = get_config(region)

    # 获取客户端对象
    client = bos_client.BosClient(config)

    upload_id = client.initiate_multipart_upload(bucket_name, obj_key).upload_id


    left_size = file_obj.size

    # left_size用于设置分块开始位置
    # 设置分块的开始偏移位置
    offset = 0

    part_number = 1
    part_list = []

    while left_size > 0:
        # 设置每块为5MB
        part_size = 5 * 1024 * 1024
        if left_size < part_size:
            part_size = left_size

        response = client.upload_part_from_file(
            bucket_name=bucket_name,
            key=obj_key,
            upload_id=upload_id,
            part_number=part_number,
            part_size=part_size,
            offset=offset,
            file_obj=file_obj,
        )

        left_size -= part_size
        offset += part_size
        part_list.append({
            "partNumber": part_number,
            "eTag": response.metadata.etag
        })

        part_number += 1

    client.complete_multipart_upload(
        bucket_name=bucket_name,
        key=obj_key,
        upload_id=upload_id,
        part_list=part_list,
    )

    # https://bucket-baiduyun.fsh.bcebos.com/image-20200324102030227.png
    return 'https://{}.{}/{}'.format(bucket_name, region, obj_key)


def delete_file(bucket, obj_key, region='fsh.bcebos.com'):
    """ 删除单个文件 """
    config = get_config(region)

    # 获取客户端对象
    client = bos_client.BosClient(config)

    # 查看文件是否存在
    try:
        response = client.get_object_meta_data(bucket, obj_key)
        print("Get meta:{}", response.metadata)
    except exception.BceError as e:
        print(e)
    else:
        client.delete_object(bucket, obj_key)


def delete_file_list(bucket, key_list, region='fsh.bcebos.com'):
    """ 批量删除文件 """
    config = get_config(region)
    # 获取客户端对象
    client = bos_client.BosClient(config)
    client.delete_multiple_objects(bucket, key_list)